package com.kili.file.config.factory;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.kili.file.config.factory.subabstract.AbstractCloudFactoryBean;
import com.kili.file.config.systemparam.FileUploadOssParamConfig;
import com.kili.file.service.FileHandleService;
import com.kili.file.service.FileUploadService;
import com.kili.file.service.impl.FileUploadWithOssCloudStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * CloudFileUploadFactoryBean
 *
 * @author jackliang
 * @date 19-4-2
 * @description
 */
@Slf4j
public class OssCloudFileUploadFactoryBean extends AbstractCloudFactoryBean implements FactoryBean<FileUploadService> {

    @Autowired
    private FileUploadOssParamConfig paramConfig;

    @Autowired
    private FileHandleService fileHandleService;

    @Override
    public FileUploadService getObject() {
        log.trace("Initialized class [" + FileUploadWithOssCloudStorage.class.getName() + "] for local file upload logically");
        fileUploadWithOssCloudStorage.setParamConfig(paramConfig);
        OSS ossClient = new OSSClientBuilder()
                .build(paramConfig.getEndpoint(),
                        paramConfig.getAccessKeyId(),
                        paramConfig.getAccessKeySecret());
        fileUploadWithOssCloudStorage.setOssClient(ossClient);
        createBucketIfNot(ossClient);
        return fileUploadWithOssCloudStorage;
    }

    @Override
    public Class<?> getObjectType() {
        return FileUploadWithOssCloudStorage.class;
    }

    @Override
    public boolean isSingleton() {
        return IS_SINGLETON;
    }

    @Override
    public Object coreWithHandler(Object o) {
        return null;//ignore
    }

    private void createBucketIfNot(OSS ossClient) {
        String bucketName = paramConfig.getBucketName();
        //Determine whether the bucket exists
        if (!ossClient.doesBucketExist(bucketName)) {
            //Create a new OSS bucket
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            //setting storage bucket permissions for public reading
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }
    }
}
